import json
import os
from datetime import datetime

from django.utils import timezone

from devops.settings import BASE_DIR
from cmdb.models import Host
from tasks.models import Task, HistoricTask
from utils.ansible_api import AnsibleClient
from django_redis import get_redis_connection

redis_cli = get_redis_connection('default')


def get_inventory():
    """
    获取主机清单
    :return:
    """
    hosts = Host.objects.all().values_list('private_ip', flat=True)
    inventory = ','.join(hosts)
    return inventory


def exec_playbook(redis_key_prefix, task_id):
    """
    执行playbook
    :param redis_key_prefix: Redis Key前缀
    :param task_id 任务id
    :return:
    """
    redis_cli.delete('{}::{}'.format(redis_key_prefix, task_id))
    hosts = Host.objects.all().values_list('private_ip', flat=True)
    sources = ','.join(hosts)
    client = AnsibleClient(sources)
    print(client)
    task = HistoricTask.objects.get(id=task_id)
    file_name = str(task.id) + '_' + datetime.now().strftime('%Y%m%d%H%M') + '.yml'
    pb_path = os.path.join(BASE_DIR, 'tmp', file_name)
    with open(pb_path, 'w') as f:
        f.write(task.content)
    client.ansible_playbook(redis_key_prefix, task_id, pb_path, extra_vars=None)
    result = redis_cli.get('{}::{}'.format(redis_key_prefix, task_id))
    task.exec_result = str(result, encoding='utf8')
    print(task.exec_result)
    task.publish_at = timezone.now()
    task.save()
    return True


def task_execute(task_id):
    """
    执行任务
    :param task_id:
    :return:
    """
    print("0000")
    print(task_id)
    redis_key_prefix = "ark::task"
    task = HistoricTask.objects.get(id=task_id)
    print("1111")
    exec_playbook(redis_key_prefix, task_id)
    print("222")
    # email_send([task.apply_user.username, task.reviewer.email], send_type='task_published', task=task.task.name, id=task.id)
    return '任务发布成功!'




